<!DOCTYPE html>
<html>
<head>
<title>管理员列表</title>
<#include "/header.html">
<link
	href="${request.contextPath}/statics/plugins/jquery-layout/jquery.layout-latest.css"
	rel="stylesheet" />
</head>
<body>
	<div class="ui-layout-west">
		<div class="main-content">
			<div class="box box-main">
				<div class="box-header">
					<div class="box-title">
						<i class="fa-square-o"></i> 组织机构
					</div>
					<div class="box-tools pull-right">
						<a type="button" class="btn btn-box-tool menuItem" href="#"
							onclick="dept()" title="管理机构"><i class="fa fa-edit"></i></a>
						<button type="button" class="btn btn-box-tool" id="btnExpand"
							title="展开" style="display: none;">
							<i class="fa fa-chevron-up"></i>
						</button>
						<button type="button" class="btn btn-box-tool" id="btnCollapse"
							title="折叠">
							<i class="fa fa-chevron-down"></i>
						</button>
						<button type="button" class="btn btn-box-tool" id="btnRefresh"
							title="刷新机构">
							<i class="fa fa-refresh"></i>
						</button>
					</div>
				</div>
				<div class="ui-layout-content">

					<div class="treeShowHideButton" onclick="search();">
						<label id="btnShow" title="显示搜索" style="display: none;">︾</label>
						<label id="btnHide" title="隐藏搜索">︽</label>
					</div>
					<div class="treeSearchInput" id="search">
						<label for="keyword">关键字：</label><input type="text" class="empty"
							id="keyword" maxlength="50">
<!-- 						<button class="btn" id="btn" onclick="searchNode()">搜索</button>
 -->					</div>
					<div id="tree" class="ztree"></div>
				</div>
			</div>
		</div>
	</div>

	<div id="rrapp" v-cloak class="container-div ui-layout-center">
		<div v-show="showList">
			<div class="grid-btn">
				<div class="form-group col-sm-2">
					<input type="text" class="form-control" v-model="q.username"
						@keyup.enter="query" placeholder="用户名">
				</div>
				<a class="btn btn-default" @click="query">查询</a>
				<#if shiro.hasPermission("sys:user:save")> <a
					class="btn btn-primary" @click="add"><i class="fa fa-plus"></i>&nbsp;新增</a>
				</#if>
				<#if shiro.hasPermission("sys:user:update")> <a
					class="btn btn-primary" @click="update"><i
					class="fa fa-pencil-square-o"></i>&nbsp;修改</a> </#if>
				<#if shiro.hasPermission("sys:user:delete")> <a
					class="btn btn-primary" @click="del"><i class="fa fa-trash-o"></i>&nbsp;删除</a>
				</#if>
			</div>
			

		<div class="col-sm-12 select-info table-striped">
			<table id="bootstrap-table" data-mobile-responsive="true"></table>
		</div>
		</div>

		<div v-show="!showList" class="panel panel-default"  >
			<div class="panel-heading">{{title}}</div>
			<form class="form-horizontal" id="form">
				<div class="form-group">
				<div class="col-sm-2 control-label">用户名</div>
				<div class="col-sm-10">
					<input type="text" class="form-control" v-model="user.username" placeholder="登录账号"/>
				</div>
			</div>
			<div class="form-group">
				<div class="col-sm-2 control-label">所属部门</div>
				<div class="col-sm-10">
					<input type="text" class="form-control" style="cursor:pointer;" v-model="user.deptName" @click="deptTree" readonly="readonly" placeholder="所属部门"/>
				</div>
			</div>
			<div class="form-group">
				<div class="col-sm-2 control-label">密码</div>
				<div class="col-sm-10">
					<input type="text" class="form-control" v-model="user.password" placeholder="密码"/>
				</div>
			</div>
			<div class="form-group">
				<div class="col-sm-2 control-label">邮箱</div>
				<div class="col-sm-10">
					<input type="text" class="form-control" v-model="user.email" placeholder="邮箱"/>
				</div>
			</div>
			<div class="form-group">
				<div class="col-sm-2 control-label">手机号</div>
				<div class="col-sm-10">
					<input type="text" class="form-control" v-model="user.mobile" placeholder="手机号"/>
				</div>
			</div>
			<div class="form-group">
				<div class="col-sm-2 control-label">角色</div>
				<div class="col-sm-10">
					<label v-for="role in roleList" class="checkbox-inline">
						<input type="checkbox" :value="role.roleId" v-model="user.roleIdList">{{role.roleName}}
					</label>
				</div>
			</div>
			<div class="form-group">
				<div class="col-sm-2 control-label">状态</div>
				<label class="radio-inline">
					<input type="radio" name="status" value="0" v-model="user.status"/> 禁用
				</label>
				<label class="radio-inline">
					<input type="radio" name="status" value="1" v-model="user.status"/> 正常
				</label>
			</div>
			<div class="form-group">
				<div class="col-sm-2 control-label"></div>
				<input type="button" class="btn btn-primary" @click="saveOrUpdate" value="确定"/>
				&nbsp;&nbsp;<input type="button" class="btn btn-warning" @click="reload" value="返回"/>
			</div>
			
			
			
			</form>

		</div>

		
	</div>

	<!-- 选择部门 -->
	<div id="deptLayer" style="display: none; padding: 10px;">
		 
	<div id="deptTree" class="ztree"></div>
	 
	</div>
	<script
		src="${request.contextPath}/statics/plugins/jquery-layout/jquery.layout-latest.js"></script>


	<!-- <script src="${request.contextPath}/statics/js/modules/sys/user.js?_${.now?long}"></script>
 -->
	<script>
	var lastValue = "", nodeList = [], key = $("#keyword");
	key.bind("focus", focusKey).bind("blur", blurKey).bind("change cut input propertychange", searchNode);
	key.bind("keydown", function (e){if(e.which == 13){searchNode();}});

	function focusKey(e) {
		if (key.hasClass("empty")) {
			key.removeClass("empty");
		}
	}

	function blurKey(e) {
		if (key.get(0).value === "") {
			key.addClass("empty");
		}
		searchNode(e);
	}

	function searchNode() {
		var value = $.trim(key.get(0).value);
		var keyType = "name";
		if (lastValue === value) {
			return;
		}
		lastValue = value;
		var nodes = ztree.getNodes();
		if (value == "") {
			showAllNode(nodes);
			return;
		}
		hideAllNode(nodes);
		nodeList = ztree.getNodesByParamFuzzy(keyType, value);
		updateNodes(nodeList);
	}
	
	function hideAllNode(nodes){
		//var ztree = $.fn.zTree.getZTreeObj("tree");
		nodes = ztree.transformToArray(nodes);
		for(var i=nodes.length-1; i>=0; i--) {
			ztree.hideNode(nodes[i]);
		}
	}

	function showAllNode(nodes){
		nodes = ztree.transformToArray(nodes);
		for(var i=nodes.length-1; i>=0; i--) {
			if(nodes[i].getParentNode()!=null){
				ztree.expandNode(nodes[i],false,false,false,false);
			}else{
				ztree.expandNode(nodes[i],true,true,false,false);
			}
			ztree.showNode(nodes[i]);
			showAllNode(nodes[i].children);
		}
	}

	function updateNodes(nodeList) {
		ztree.showNodes(nodeList);
		for(var i=0, l=nodeList.length; i<l; i++) {
			var treeNode = nodeList[i];
			showChildren(treeNode);
			showParent(treeNode)
		}
	}

	function showChildren(treeNode){
		if (treeNode.isParent){
			for(var idx in treeNode.children){
				var node = treeNode.children[idx];
				ztree.showNode(node);
				showChildren(node);
			}
		}
	}
	function showParent(treeNode){
		var parentNode;
		while((parentNode = treeNode.getParentNode()) != null){
			ztree.showNode(parentNode);
			ztree.expandNode(parentNode, true, false, false);
			treeNode = parentNode;
		}
	}



	
	
		var setting = {
			/* view : {
				selectedMulti : false
				//dblClickExpand : false
			},
 */
			callback : {

				onClick : function(event, treeId, treeNode) {
					ztree.expandNode(treeNode);

					var opt = {
						query : {
							deptId : treeNode.deptId,
						}
					}
					$('#bootstrap-table').bootstrapTable('refresh', opt);

				}
			},
			data : {

				simpleData : {
					enable : true,
					idKey : "deptId",
					pIdKey : "parentId",
					rootPId : -1
				},
				key : {
					url : "nourl"
				},

			}
		};

		var ztree;

		function zTreeOnClick(event, treeId, treeNode) {
			alert(treeNode.tId + ", " + treeNode.name);
		};
		function queryDeptTreeDaTa()

		{
			// 树结构初始化加载
			var loadTree = function() {
				$.get(baseURL + "sys/dept/select", function(r) {
					console.info(setting);
					ztree = $.fn.zTree.init($("#tree"), setting, r.deptList); //.expandAll(true);
					// 展开第一级节点
					var node = ztree.getNodeByParam("deptId", 0);
					ztree.selectNode(node);
				});
			};
			loadTree();

			$('#btnExpand').click(function() {
				ztree.expandAll(true);
				$(this).hide();
				$('#btnCollapse').show();
			});
			$('#btnCollapse').click(function() {
				ztree.expandAll(false);
				$(this).hide();
				$('#btnExpand').show();
			});
			$('#btnRefresh').click(function() {
				loadTree();
			});
		}

		$(document)
				.ready(
						function() {
							$('body').layout({
								west__size : 185
							});
							/* queryUserList();*/
							queryDeptTreeDaTa();
							$('#bootstrap-table')
									.bootstrapTable(
											{
												method : 'get', // 服务器数据的请求方式 get or post
												url : baseURL + 'sys/user/list', // 服务器数据的加载地址
												 showRefresh : true,
												 showToggle : true,
												 showColumns : true,
												 showExport :true,
												 sortable: true,                                  
												 sortName:"userId",// 排序列名称
								                 sortOrder: "desc",    
												iconSize : 'outline',
												toolbar : '#exampleToolbar',
 												striped : true, // 设置为true会有隔行变色效果
												dataType : "json", // 服务器返回的数据类型
												pagination : true, // 设置为true会在底部显示分页条
												// queryParamsType : "limit",
												// //设置为limit则会发送符合RESTFull格式的参数
												singleSelect : false, // 设置为true将禁止多选
												// contentType : "application/x-www-form-urlencoded",
												// //发送到服务器的数据编码类型
												pageSize : 10, // 如果设置了分页，每页数据条数
												pageNumber : 1, // 如果设置了分布，首页页码
												// search : true, // 是否显示搜索框
												//showColumns : false, // 是否显示内容下拉框（选择显示的列）
												sidePagination : "server", // 设置在哪里进行分页，可选值为"client" 或者
												// "server"
												queryParams : function(params) {
 													return {
														// 说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,以及所有列的键值对
														limit : params.limit,
														offset : params.offset,
														username : vm.q.username,
														sidx: params.sort,      //排序列名  
														order: params.order //排位命令（desc，asc） 
														/* sort:"userId",
														order:"desc" */
 													};
												},
												// //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
												// queryParamsType = 'limit' ,返回参数必须包含
												// limit, offset, search, sort, order 否则, 需要包含:
												// pageSize, pageNumber, searchText, sortName,
												// sortOrder.
												// 返回false将会终止请求
												columns : [
														{
															checkbox : true
														},
														{
															field : 'userId', // 列字段名
															title : '序号', // 列标题
															sortable: true
														},
														{
															field : 'username',
															title : '姓名'
														},
														{
															field : 'deptName',
															title : '用户名'
														},
														{
															field : 'email',
															title : '邮箱'
														},
														{
															field : 'status',
															title : '状态',
															align : 'center',
															formatter : function(
																	value, row,
																	index) {
																if (value == '0') {
																	return '<span class="label label-danger">禁用</span>';
																} else if (value == '1') {
																	return '<span class="label label-primary">正常</span>';
																}
															}
														},
														{
															title : '操作',
															field : 'id',
															align : 'center',
															formatter : function(
																	value, row,
																	index) {
																var e = '<a  class="btn btn-primary btn-sm '
																		+ ''
																		+ '" href="#" mce_href="#" title="编辑" onclick="edit(\''
																		+ row.userId
																		+ '\')"><i class="fa fa-edit "></i></a> ';
																var d = '<a class="btn btn-warning btn-sm '
																		+ ''
																		+ '" href="#" title="删除"  mce_href="#" onclick="remove(\''
																		+ row.userId
																		+ '\')"><i class="fa fa-remove"></i></a> ';
															 
																return e + d;
																		
															}
														} ]
											});
						});

		var deptTree;
	
		var vm = new Vue({
			el : '#rrapp',
			data : {
				q : {
					username : null
				},
				showList : true,
				title : null,
				roleList : {},
				user : {
					status : 1,
					deptId : null,
					deptName : null,
					roleIdList : []
				},
				dept : {
					parentName : null,
					parentId : 0,
					orderNum : 0
				}
			},
			methods : {
				query : function() {
					vm.reload();
				},
				add : function() {
					vm.showList = false;
					vm.title = "新增";
					vm.roleList = {};
					vm.user = {
						deptName : null,
						deptId : null,
						status : 1,
						roleIdList : []
					};

					//获取角色信息
					this.getRoleList();

					vm.getDept();
				},
				getDept : function() {
					//加载部门树
					$.get(baseURL + "sys/dept/list", function(r) {
						deptTree = $.fn.zTree.init($("#deptTree"), setting, r);
						var node = ztree.getNodeByParam("deptId",
								vm.user.deptId);
						if (node != null) {
							deptTree.selectNode(node);

							vm.user.deptName = node.name;
						}
					})
				},
				update : function() {
					var userId = getSelectedRow();
					if (userId == null) {
						return;
					}

					vm.showList = false;
					vm.title = "修改";

					vm.getUser(userId.userId);
					//获取角色信息
					this.getRoleList();
				},
				del : function() {
					var userIds = getSelectedRows();
					if (userIds == null) {
						return;
					}
					userIds = $.map(userIds, function(row) {
						return row.userId;
					});
					confirm('确定要删除选中的记录？', function() {
						$.ajax({
							type : "POST",
							url : baseURL + "sys/user/delete",
							contentType : "application/json",
							data : JSON.stringify(userIds),
							success : function(r) {
								if (r.code == 0) {
									alert('操作成功', function() {
										vm.reload();
									});
								} else {
									alert(r.msg);
								}
							}
						});
					});
				},
				saveOrUpdate : function() {
					var url = vm.user.userId == null ? "sys/user/save"
							: "sys/user/update";
					$.ajax({
						type : "POST",
						url : baseURL + url,
						contentType : "application/json",
						data : JSON.stringify(vm.user),
						success : function(r) {
							if (r.code === 0) {
								alert('操作成功', function() {
									vm.reload();
								});
							} else {
								alert(r.msg);
							}
						}
					});
				},
				getUser : function(userId) {
					$.get(baseURL + "sys/user/info/" + userId, function(r) {
						vm.user = r.user;
						vm.user.password = null;

						vm.getDept();
					});
				},
				getRoleList : function() {
					$.get(baseURL + "sys/role/select", function(r) {
						vm.roleList = r.list;
					});
				},
				deptTree : function() {
					layer.open({
						type : 1,
						offset : '50px',
						skin : 'layui-layer-molv',
						title : "选择部门",
						area : [ '300px', '450px' ],
						shade : 0,
						shadeClose : false,
						content : jQuery("#deptLayer"),
						btn : [ '确定', '取消' ],
						btn1 : function(index) {
							var node = deptTree.getSelectedNodes();
							//选择上级部门
							vm.user.deptId = node[0].deptId;
							vm.user.deptName = node[0].name;

							layer.close(index);
						}
					});
				},
				reload : function() {
					vm.showList = true;
					$('#bootstrap-table').bootstrapTable('refresh',
							vm.q.username);

				}
			}
		});

		function search($this) {
			$('#search').slideToggle(200);
			$('#btnShow').toggle();
			$('#btnHide').toggle();
			$('#keyword').focus();
		}

		function edit(id) {

			layer.open({
				type : 2,
				title : '编辑',
				maxmin : true,
				//shadeClose : false, // 点击遮罩关闭层
				area : [ '800px', '520px' ],
				content : "edit.html?userId=" + id // iframe的url
			});
		}

		function remove(id) {
			var arr = new Array();
			arr.push(id);
			confirm('确定要删除选中的记录？', function() {

				$.ajax({
					type : "POST",
					url : baseURL + "sys/user/delete",
					contentType : "application/json",
					data : JSON.stringify(arr),
					success : function(r) {
						if (r.code == 0) {
							alert('操作成功', function() {
								vm.reload();
							});
						} else {
							alert(r.msg);
						}
					}
				});
			});
		}
	</script>
	
	
</body>
</html>